package com.yun.datastructure.tree.heap;

public class MinHeap {
    int[] array;
    int size;

    public MinHeap(int capacity) {
        this.array = new int[capacity];
    }

    public MinHeap(int[] nums) {
        this.array = nums;
        this.size = nums.length;
        ;
        heapify();
    }

    //建堆
    private void heapify() {
        for (int i = size / 2 - 1; i > 0; i--) {
            down(i);
        }
    }

    //下潜
    private void down(int parent) {
        int left = parent * 2 + 1;
        int right = parent * 2 + 2;
        int min = parent;
        if (left < size && array[left] < array[min]) {
            min = left;
        }
        if (right < size && array[right] < array[min]) {
            min = right;
        }
        if (min != parent) {
            swap(min, parent);
            down(min);
        }
    }

    //交换数组中的2个元素
    private void swap(int i, int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }

    //添加元素
    public boolean offer(int offered) {
        if (isFull()) {
            return false;
        }
        size++;
        up(offered);
        return true;
    }

    //上浮
    private void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (size - 1) / 2;
            if (offered < array[parent]) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    /**
     * 删除堆顶元素
     *
     * @return 堆顶元素
     */
    public int poll() {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        int top = array[0];
        swap(0, size - 1);
        size--;
        down(0);
        return top;
    }

    /**
     * 返回堆顶元素
     *
     * @return 堆顶元素
     */
    public int peek() {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        return array[0];
    }

    public int replace(int replaced) {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        int remove=array[0];
        array[0] = replaced;
        down(0);
        return remove;
    }

    public int replace(int replaced, int index) {
        if (isEmpty()) {
            throw new NullPointerException();
        }
        int remove=array[index];
        array[index] = replaced;
        down(index);
        return remove;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == array.length;
    }
}
